package com.fastjars.shiro.realm;

import com.fastjars.shiro.InitializingUserService;
import com.fastjars.shiro.UserService;
import com.fastjars.shiro.authc.AccountNotFoundException;
import com.fastjars.shiro.model.User;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * AbstractRealm
 *
 * @author Brant Liu <br> 邮箱：<br>lbf1988@qq.com <br>日期：<br>2018/10/10
 * @version 1.0.0
 */
public abstract class AbstractRealm extends AuthorizingRealm implements ApplicationContextAware,InitializingUserService {
    private ApplicationContext context;

    private UserService userService;

    @Override
    public void setService(UserService serviceBean) {
        this.userService = serviceBean;
    }

    protected UserService getUserService() {
        if(null == userService){
            userService = context.getBean(UserService.class);
        }
        return userService;
    }

    /**
     * 验证用户凭证
     * @param token
     * @return
     */
    protected User validatePrincipal(AuthenticationToken token){
        String username = String.valueOf(token.getPrincipal());
        User userToken = (User) getUserService().query(username);
        if(null == userToken){
            throw new AccountNotFoundException(String.format("account[%s] not fount",username));
        }
        return userToken;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(getUserService().getRoles());
        info.setStringPermissions(getUserService().getStringPermissions());
        return info;
    }
}
